package cn.nb12.xbox.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Controller
public class GenController extends BaseController{
	
	/**
	 * 首页
	 * @param view
	 * @return
	 */
	@RequestMapping("index")
	public ModelAndView doMain(ModelAndView view) {
		view.setViewName("pages/index");
		return view;
	}
	
	/**
	 * 设置语言
	 * @param view
	 * @param request
	 * @return
	 */
	@RequestMapping("go_charset")
	public ModelAndView goCharset(ModelAndView view,HttpServletRequest request) {
		view.setViewName("pages/comm/charset");
		view.getModel().put("title", exceptionInfo.getMessage(request, messageSource, "msg.code.0000000005"));
		Map<String,String> data=new HashMap<>();
		data.put("zh-CN", "中文");
		data.put("en-US", "English");
		view.getModel().put("data", data);
		return view;
	}
	
	/**
	 * 设置编码
	 * @param charset
	 * @return
	 */
	@RequestMapping("doCharSet")
	public ModelAndView doCharSet(ModelAndView view,String charset,HttpServletRequest request) {
		try {
			log.info((String) request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME));
			if(charset==null || charset.trim().length()<1) {
				throw new Exception("error.code.0000000003");
			}
			if("zh-CN".equals(charset.trim())){
	            Locale locale = new Locale("zh", "CN"); 
	            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
	        }
	        else if("en-US".equals(charset.trim())){
	            Locale locale = new Locale("en", "US"); 
	            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
	        }
	        else {
	        	 request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());        
	        }
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		view.setViewName("redirect:go_charset.do");
		return view;
	}
}
